﻿using System;
using System.Web.Mvc;
using HomeService.Models;

namespace HomeService.Infrastructure
{
    public class ServiceRequestBinder : IModelBinder
    {
        private const string SessionKey = "_serviceRequest";

        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            if (bindingContext.Model != null)
                throw new InvalidOperationException("Cannot update instances.");
            if (controllerContext.HttpContext.Session == null)
                throw new Exception("Session shouldn't be null.");

            var serviceRequest = (ServiceRequest) controllerContext.HttpContext.Session[SessionKey];
            if (serviceRequest == null) {
                serviceRequest = new ServiceRequest();
                controllerContext.HttpContext.Session[SessionKey] = serviceRequest;
            }
            return serviceRequest;
        }
    }
}